package com.jf.identity.datasource;

import com.jf.identity.config.MachineConfig;
import com.jf.identity.holder.DataSourceKeyHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态数据源
 *
 * @author FCG
 */
@Component("dataSource")
public class DynamicDataSource extends AbstractRoutingDataSource {
    private final DataSourceKeyHolder dataSourceKeyHolder;
    private final TargetDataSource targetDataSource;
    private final MachineConfig machineConfig;

    @Autowired
    public DynamicDataSource(DataSourceKeyHolder dataSourceKeyHolder,
                             TargetDataSource targetDataSource,
                             MachineConfig machineConfig) {
        this.dataSourceKeyHolder = dataSourceKeyHolder;
        this.targetDataSource = targetDataSource;
        this.machineConfig = machineConfig;

    }

    @Override
    protected Object determineCurrentLookupKey() {
        String key = dataSourceKeyHolder.getDataSourceKey();
//        return Optional.ofNullable(key).orElseThrow(() -> new IllegalStateException("动态数据源未初始化"));
        return key;
    }

    /**
     * 根据machine.config配置多个数据源
     */
    @Override
    public void afterPropertiesSet() {
        DataSource ds = targetDataSource.getDefaultDataSource(machineConfig);
        Map<String, DataSource> targetDataSources = new HashMap<>(1);
        targetDataSources.put(TargetDataSource.jfVisDb, ds);
        Map<Object, Object> dataSources = new HashMap<>(targetDataSources.size());
        targetDataSources.forEach(dataSources::put);
        setTargetDataSources(dataSources);
        //配置默认数据源
        setDefaultTargetDataSource(ds);
        super.afterPropertiesSet();
    }

    public void resolveDataSource() {
        super.afterPropertiesSet();
    }

}
